package cn.edu.zzuli;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Date: 2021/3/7 10:09
 * @Author: 绯色下午茶
 * @Description: 举例说明集合类是不安全的
 */
public class NotSafeDemo {
    public static void main(String []args){
        Map<String, String> map = new ConcurrentHashMap<>();//Collections.synchronizedMap(new HashMap<>());//new HashMap<>();
        for (int i = 0; i < 300; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, i + "").start();
        }
    }
    public void setNotSafe() {

        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 300; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }, i + "").start();
        }
    }


    public void listNotSafe() {

        List<String> list = new CopyOnWriteArrayList(); //Collections.synchronizedList(new ArrayList<>());//new Vector<>();
        System.out.println(1234);

//        Iterator iterator = list.iterator();
//        while (iterator.hasNext()){
//            System.out.println(iterator.next());
//        }
//        list.add(UUID.randomUUID().toString().substring(0,8));
//        System.out.println(list);
        /**
         * 故障现象：
         *  java.util.ConcurrentModificationException
         *  导致原因
         *
         *  解决方案
         *      1.使用vector
         *      2.List<String> list = Collections.synchronizedList(new ArrayList<>());
         *      3.List<String> list = new CopyOnWriteArrayList();
         *  优化建议（同样的错误不要出现第二次）
         */
        for (int i = 0; i < 300; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, i + "").start();
        }
    }
}
